import java.util.LinkedList;
import java.util.Queue;

public class Solution1 {
    int m;
    int n;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] check;
    Queue<int[]> q;
    public int nearestExit(char[][] maze, int[] entrance) {
        m = maze.length;
        n = maze[0].length;
        check = new boolean[m][n];
        q = new LinkedList<>();
        q.add(new int[]{entrance[0], entrance[1]});
        check[entrance[0]][entrance[1]] = true;
        int ret = 0;

        while(!q.isEmpty()) {
            ret++;
            int sz = q.size();
            for(int j = 0; j < sz; j++) {
                int[] t = q.poll();
                int a = t[0];
                int b = t[1];
                for(int k = 0; k < 4; k++) {
                    int x = a + dx[k];
                    int y = b + dy[k];
                    if(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.' && check[x][y] == false) {
                        q.add(new int[]{x, y});
                        check[x][y] = true;
                        if(x == 0 || x == m - 1 || y == 0 || y == n - 1) {
                            return ret;
                        }
                    }
                }
            }
        }
        return -1;
    }
}
